import axios from 'axios';
import qs from 'qs';
import crypto from 'crypto';
import Router from '../router';
import appService from './appService';
import { Message } from 'view-design';

let axiosInstance = null;
const CancelToken = axios.CancelToken;
/** 未完成操作缓存池 */
const pendings = {};
/** 未完成操作缓存池key */
function getPendingKey(request) {
  let key;
  if (request.method.toLowerCase() === 'get' || request.method.toLowerCase() === 'delete') {
    key = request.url + '&' + request.method;
  } else {
    key = request.url + '&' + request.method + JSON.stringify(request.data);
  }
  const sha1 = crypto.createHash('sha1');
  sha1.update(key);
  return sha1.digest('hex');
}
/** 移除未完成操作 */
function removePending(request) {
  const key = getPendingKey(request);
  if (pendings[key]) {
    pendings[key]('CANCELED');
    delete pendings[key];
  }
}
/** 新增未完成操作 */
function addPending(request, cancle) {
  const key = getPendingKey(request);
  pendings[key] = cancle;
}
/** 创建axios实例 */
function axiosCreateInstance() {
  const axiosInstance = axios.create({
    /** 将自动加在 `url` 前面，除非 `url` 是一个绝对 URL */
    //baseURL: serverPath,

    /** 设置超时时间 */
    timeout: 60 * 1000
    /** 设置请求头 */
    //headers: { 'Content-type': 'application/x-www-form-urlencoded' },
  });
  /** 不允许携带cookie请求 */
  axiosInstance.defaults.withCredentials = false;
  delete axiosInstance.defaults.headers.post['Content-Type'];
  delete axiosInstance.defaults.headers.patch['Content-Type'];
  delete axiosInstance.defaults.headers.put['Content-Type'];
  /** 请求拦截 */
  axiosInstance.interceptors.request.use(request => {
    /** 如果是文件上传，删除contentType,否则无法正常上传 */
    if (request.data && request.data instanceof FormData) {
      delete request.headers.common['Content-type'];
    }
    /** 关闭未完成的相同的请求 */
    removePending(request);
    request.cancelToken = new CancelToken((cancle) => {
      /** 添加未完成操作 */
      addPending(request, cancle);
    });
    return request;
  }, error => {
    return Promise.reject(error);
  });
  /** 响应拦截器 */
  axiosInstance.interceptors.response.use(function (response) {
    console.log(response, 'response');
    if (response.data.errorCode === 403 || response.data.errorCode === 405 || response.data.errorCode === 406) { //997
      Message.error({
        content: '账号授权异常,请重新登录！'
      });
      window.setTimeout(() => {
        appService.removeUserInfo();
        Router.push('/');
      }, 1000);
      return;
      // Router.push('/');
    }
    /** 20002: token错误, 9999: 网络异常 , */
    if (response.data.errorCode === 20002) {
      window.setInterval(() => {
        appService.removeUserInfo();
        Router.push('/');
      }, 500);
    }
    if (response.data.errorCode === 9999) {
        Message.error({
          content: '网络异常,请重试'
        });
    }
    return response;
  }, function (error) {
    return error.response;
  });
  return axiosInstance;
}

/**
 * config.params是即将与请求一起发送的 URL 参数,必须是一个无格式对象(plain object)或 URLSearchParams 对象。
 * config.data是作为请求主体被发送的数据,只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
 */
function request(url, config) {
  if (!axiosInstance) {
    axiosInstance = axiosCreateInstance();
  }
  /** 请求头添加token */
  // let userInfo = storage.getUserInfo();
  // if (userInfo) {
  //   axiosInstance.defaults.headers.common['Content-type'] = userInfo.linuxprobeToken;
  // }
  return axiosInstance.request(url, config);
}

/** 执行get请求 */
function getRequest(url, params, config) {
  if (!axiosInstance) {
    axiosInstance = axiosCreateInstance();
  }
  axiosInstance.defaults.headers.common['Content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  let slipt = '?';
  if (url.indexOf('?') !== -1) {
    slipt = '&';
  };
  //请求时去掉空的字段
  for (const key in params) {
    if (!params[key]) {
      delete params[key];
    }
  };
  return axiosInstance.get(`${url}${slipt}${qs.stringify(params, { allowDots: true, arrayFormat: 'repeat' })}`, config);
}

/** 执行delete请求 */
function deleteRequest(url, params, config) {
  if (!axiosInstance) {
    axiosInstance = axiosCreateInstance();
  }
  let slipt = '?';
  if (url.indexOf('?') !== -1) {
    slipt = '&';
  }
  axiosInstance.defaults.headers.common['Content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  return axiosInstance.delete(`${url}${slipt}${qs.stringify(params, { allowDots: true })}`, config);
}

/** 执行put请求 */
function putRequest(url, data, config) {
  if (!axiosInstance) {
    axiosInstance = axiosCreateInstance();
  }
  if (!config) {
    config = {};
  }
  if (!config.headers) {
    config.headers = {};
  }
  if (!config.headers['Content-type']) {
    config.headers['Content-type'] = '';
  }
  axiosInstance.defaults.headers.common['Content-type'] = 'application/json;charset=UTF-8';
  return axiosInstance.put(url, data, config);
}

/** 执行post请求 */
function postRequest(url, data, config) {
  if (!axiosInstance) {
    axiosInstance = axiosCreateInstance();
  }
  if (!config) {
    config = {};
  }
  if (!config.headers) {
    config.headers = {};
  }
  if (!config.headers['Content-type']) {
    config.headers['Content-type'] = '';
  }
  axiosInstance.defaults.headers.common['Content-type'] = 'application/json;charset=UTF-8';
  return axiosInstance.post(url, data, config);
}

/** 执行post请求 */
function postRequestForm(url, data, config) {
  if (!axiosInstance) {
    axiosInstance = axiosCreateInstance();
  }
  if (!config) {
    config = {};
  }
  if (!config.headers) {
    config.headers = {};
  }
  if (!config.headers['Content-type']) {
    config.headers['Content-type'] = '';
  }
  axiosInstance.defaults.headers.common['Content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  return axiosInstance.post(url, data, config);
}

export default {
  request: request,
  getRequest: getRequest,
  putRequest: putRequest,
  deleteRequest: deleteRequest,
  postRequest: postRequest,
  postRequestForm: postRequestForm
};
